<template>
  <div class="category-management">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="分类名称">
          <el-input v-model="searchForm.categoryName" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item label="显示状态">
          <el-select  style="width: 120px;" v-model="searchForm.isVisible" placeholder="请选择状态" clearable>
            <el-option label="全部" :value="null" />
            <el-option label="显示" value="1" />
            <el-option label="隐藏" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置刷新</el-button>
          <el-button type="success" @click="showAddDialog">添加分类</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="tableData" border stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="categoryId" label="ID" width="80" align="center" />
        <el-table-column prop="categoryName" label="分类名称" width="150" align="center" />
        <el-table-column prop="categorySort" label="排序" width="80" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.isVisible" active-value="1" inactive-value="0" 
                      active-color="#13ce66" inactive-color="#ff4949" 
                      @change="changeStatus(row.categoryId, row.isVisible)" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.categoryId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-area">
      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[5, 10, 20, 30]" 
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 添加分类对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加课程分类" width="600px">
      <el-form :model="addForm" label-width="100px" :rules="addRules" ref="addFormRef">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="addForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序权重" prop="categorySort">
          <el-input-number v-model="addForm.categorySort" :min="0" :max="999" />
          <span class="tip">(数字越大越靠前)</span>
        </el-form-item>
        <el-form-item label="显示状态" prop="isVisible">
          <el-switch v-model="addForm.isVisible" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑课程分类" width="600px">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="editForm.categoryName" />
        </el-form-item>
        <el-form-item label="排序权重" prop="categorySort">
          <el-input-number v-model="editForm.categorySort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="显示状态" prop="isVisible">
          <el-switch v-model="editForm.isVisible" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCategoryPage, 
  addCategory, 
  updateCategory, 
  deleteCategory, 
  changeCategoryStatus 
} from '@/api/courseCategory'

// 数据定义
const tableData = ref([])
const loading = ref(false)
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const addFormRef = ref()
const editFormRef = ref()

// 搜索表单
const searchForm = reactive({
  categoryName: '',
  isVisible: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 添加表单数据
const addForm = reactive({
  categoryName: '',
  categorySort: 0,
  isVisible: '1'
})

// 添加表单验证规则
const addRules = reactive({
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  categorySort: [
    { required: true, message: '请输入排序权重', trigger: 'blur' }
  ]
})

// 编辑表单数据
const editForm = reactive({
  categoryId: null,
  categoryName: '',
  categorySort: 0,
  isVisible: '1'
})

// 编辑表单验证规则
const editRules = reactive({
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  categorySort: [
    { required: true, message: '请输入排序权重', trigger: 'blur' }
  ]
})

// 初始化加载数据
onMounted(() => {
  fetchCategoryList()
})

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    loading.value = true
    const params = {
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getCategoryPage(params)
    if (res.code === 200) {
      tableData.value = res.data.page.records
      pagination.total = res.data.page.total
    }
  } catch (error) {
    console.error('获取课程分类列表失败:', error)
    ElMessage.error('获取课程分类列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchCategoryList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.categoryName = ''
  searchForm.isVisible = null
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchCategoryList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchCategoryList()
}

// 显示添加对话框
const showAddDialog = () => {
  resetAddForm()
  addDialogVisible.value = true
}

// 重置添加表单
const resetAddForm = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    categoryName: '',
    categorySort: 0,
    isVisible: '1'
  })
}

// 提交添加表单
const submitAddForm = async () => {
  try {
    await addFormRef.value.validate()
    
    await addCategory(addForm)
    ElMessage.success('添加成功')
    addDialogVisible.value = false
    fetchCategoryList()
  } catch (error) {
    console.error('添加失败:', error)
  }
}

// 显示编辑对话框
const showEditDialog = (row) => {
  Object.assign(editForm, {
    categoryId: row.categoryId,
    categoryName: row.categoryName,
    categorySort: row.categorySort,
    isVisible: row.isVisible
  })
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const params = {
      categoryId: editForm.categoryId,
      categoryName: editForm.categoryName,
      categorySort: editForm.categorySort,
      isVisible: editForm.isVisible
    }
    
    await updateCategory(params)
    ElMessage.success('更新成功')
    editDialogVisible.value = false
    fetchCategoryList()
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 删除分类
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该课程分类吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCategory(id)
    ElMessage.success('删除成功')
    fetchCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 修改状态
const changeStatus = async (id, isVisible) => {
  try {
    await changeCategoryStatus(id, isVisible)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    const item = tableData.value.find(item => item.categoryId === id)
    if (item) item.isVisible = isVisible === '1' ? '0' : '1'
  }
}
</script>

<style scoped>
.category-management {
  padding: 20px;
  background-color: #fff;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.tip {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
</style>